package com.xiao.sulinguser.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.xiao.sulinguser.constant.RedisConstant;
import com.xiao.sulinguser.entity.MemberEntity;
import com.xiao.sulinguser.service.MemberService;
import com.xiao.sulinguser.service.RegisterService;
import com.xiao.sulinguser.vo.UserSubmitVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: 1322127758@qq.com
 * @date: 2022/3/13 17:16
 * @作用:
 */
@Service("registerService")
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;

    @Override
    public String saveUser(UserSubmitVo userSubmitVo) {

        /**
         * 1.从redis中获取验证码
         */
        //用户存验证码的key
        String codeKey = RedisConstant.CODE_USER_REDIS + userSubmitVo.getMobile();
        String s = redisTemplate.opsForValue().get(codeKey);
        //判断获取到的数据
        if(!StringUtils.isEmpty(s)){
            /**
             * 2.判断验证码是否一致
             */
            String code = s.split("-")[0];
            if(code.equals(userSubmitVo.getCode())){
                /*
                 * 3.拿手机号/账号 去数据库中查询用户看看用户是否已存在
                 * HINT 这里可以加锁
                 */
                MemberEntity memberEntity = memberService.selectUser(Long.valueOf(userSubmitVo.getMobile()), userSubmitVo.getUsername());
                //判断用户是否已存在
                if(null == memberEntity){
                    //4.不存在删除redis中的验证码
                    redisTemplate.delete(codeKey);
                    //5.MD5盐值加密一下密码
                    //5.加密密码
                    //创建加密用的对象
                    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                    //加密后的密码
                    String encode = bCryptPasswordEncoder.encode(userSubmitVo.getPassword());

                    MemberEntity memberEntity1 = new MemberEntity();
                    BeanUtils.copyProperties(userSubmitVo,memberEntity1);
                    memberEntity1.setPassword(encode);
                    memberEntity1.setCreateTime(new Date());
                    //7.保存数据
                    boolean save = memberService.save(memberEntity1);
                    if(save){
                        return "200";
                    }
                }else{
                    return "账号或者手机号已存在!";
                }
            }
        }
        return "验证码效验不通过!";
    }
}
